package com.senlin.ethereum.infura;

import com.google.gson.Gson;
import com.senlin.ethereum.common.Constant;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.Optional;

// https://faucet.ropsten.be/donate/<你的账户地址>

/**
 * @author huwei
 */
@Slf4j
public class InfuraClient {
    private static final OkHttpClient httpClient = new OkHttpClient();
    private InfuraClient() {
        throw new IllegalStateException();
    }

    public static class Ropsten {

        public Optional<RopstenDonate> requestAndGetEther(String address) {
            Request request = new Request.Builder()
                    .url(MessageFormat.format(EndPoint.Ropsten.donateAddr, address))
                    .build();

            try (Response response = httpClient.newCall(request).execute()) {
                String data = response.body().string();
                log.info("{}Ropsten requestAndGetEther body = {}", Constant.EthErrorPrint.header, data);
                if (response.isSuccessful())
                    return Optional.of(new Gson().fromJson(data, RopstenDonate.class));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return Optional.empty();
        }
    }


    public enum EndPoint {
        Ropsten("https://ropsten.infura.io/v3/21c68ca446714198aae1e95cc0c2945c",
                "https://faucet.ropsten.be/donate/{0}");

        private String nodeAddr;
        private String donateAddr;
        EndPoint(String nodeAddr, String donateAddr) {
            this.nodeAddr = nodeAddr;
            this.donateAddr = donateAddr;
        }
        public String getNodeAddr() { return this.nodeAddr; }
        public String getDonateAddr() {
            return this.donateAddr;
        }
    }

    @Getter
    @Setter
    @ToString
    public static class RopstenDonate {
        private String address;
        private String txHash;
        private BigInteger amount;
    }
}
